package cn.hairui.blog.controller;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.Message;
import cn.hairui.blog.model.Messagereply;
import cn.hairui.blog.model.User;
import cn.hairui.blog.model.WebInfo;
import cn.hairui.blog.service.MessageService;
import cn.hairui.blog.service.WebInfoService;
import cn.hairui.blog.util.DateUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * <h2>请添加说明
 * </h2>
 * <ol>请添加详细说明
 * </ol>
 *
 * <h2>修改历史
 * </h2>
 * <ol>如有修改，请添加修改历史
 * </ol>
 *
 * </p>
 *
 * @author laoganbu
 * @version V1.0
 * @date 2019/8/26 16:47
 */
@Controller

public class MessageController {
    @Autowired
    private WebInfoService webInfoService;

    @Autowired
    private MessageService messageService;

    private String ORIGINMSGID_STR = "IDNO_";
    private String REPLYMSGID_STR = "RIDNO_";

    @RequestMapping(value = "message")
    public String message(HttpServletRequest request, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);
        int pageSize = 5;//默认每页显示记录数量
        Integer pageNum = null;
        String pageNumStr = request.getParameter("pageIndex");
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Map> messageList = messageService.listMap();
        PageInfo<Map> pageInfo = new PageInfo<Map>(messageList);

        List<Map> messages = new ArrayList<>();
        Iterator iterator = messageList.iterator();
        while (iterator.hasNext()) {
            Map messageMap = (Map) iterator.next();
            int msgId = (int) messageMap.get("id");
            //通过msgId获取回复信息
            List<Map> replyMsgList = messageService.listReply(msgId);
            messageMap.put("reply", replyMsgList);
            messages.add(messageMap);
        }
        model.addAttribute("messages", messages);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("pageIndex", pageNum);
        model.addAttribute("pageSize", pageSize);
        return "message";
    }

    @RequestMapping(value = "leavemsg")
    @ResponseBody
    public String leavemsg(HttpServletRequest request, Model model) {
        Map map = new HashMap();

        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo == null) {
            map.put(PubConstant.flag, PubConstant.permissions);
        } else {

            try {
                String content = request.getParameter("content");
                String username = userinfo.getUsername();
                String time = DateUtil.getCurrentTime();

                Message message = new Message();
                message.setUsername(username);
                message.setContent(content);
                message.setMessageTime(time);
                message.setStatus(PubConstant.STS_1);
                messageService.add(message);
                map.put(PubConstant.flag, PubConstant.success);
            } catch (Exception e) {
                e.printStackTrace();
                map.put(PubConstant.flag, PubConstant.failed);
            }
        }
        return JSONUtils.toJSONString(map);
    }

    @RequestMapping(value = "messagereply")
    @ResponseBody
    public String messagereply(HttpServletRequest request, Model model) {
        Map map = new HashMap();
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo == null) {
            map.put(PubConstant.flag, PubConstant.permissions);
        } else {
            String messageId = request.getParameter("messageId");
            String replyContent = request.getParameter("replyContent");
            //这里需要与前台约定
            if (messageId != null) {
                messageId = messageId.toUpperCase();
                if (messageId.startsWith(ORIGINMSGID_STR)) {
                    //原留言回复
                    int msgid = msgid = Integer.parseInt(messageId.split(ORIGINMSGID_STR)[1]);
                    Message message = messageService.find(msgid);
                    String fromuser = userinfo.getUsername();
                    String touser = message.getUsername();
                    String content = replyContent;
                    String replytime = DateUtil.getCurrentTime();

                    Messagereply messagereply = new Messagereply();
                    messagereply.setMsgid(msgid);
                    messagereply.setFromuser(fromuser);
                    messagereply.setTouser(touser);
                    messagereply.setContent(content);
                    messagereply.setReplytime(replytime);
                    messagereply.setStatus(PubConstant.STS_0);
                    messageService.addReply(messagereply);
                    map.put(PubConstant.flag, PubConstant.success);

                } else if (messageId.startsWith(REPLYMSGID_STR)) {
                    //回复回复留言
                    int msgreplyid = Integer.parseInt(messageId.split(REPLYMSGID_STR)[1]);
                    Messagereply messagereply = messageService.findReply(msgreplyid);
                    System.out.println(messagereply);
                    String fromuser = userinfo.getUsername();
                    String touser = messagereply.getFromuser();
                    String content = replyContent;
                    String replytime = DateUtil.getCurrentTime();

                    Messagereply domain = new Messagereply();
                    domain.setMsgid(messagereply.getMsgid());
                    domain.setFromuser(fromuser);
                    domain.setTouser(touser);
                    domain.setContent(content);
                    domain.setReplytime(replytime);
                    domain.setStatus(PubConstant.STS_0);
                    messageService.addReply(domain);
                    map.put(PubConstant.flag, PubConstant.success);
                }
            } else {
                map.put(PubConstant.flag, PubConstant.failed);
            }
        }
        return JSONUtils.toJSONString(map);
    }

}
